package com.example.multithread.no1195;

import java.util.concurrent.Semaphore;

public class SemaphoreFizzBuzz {

    private int n;
    Semaphore fizzSem = new Semaphore(0);
    Semaphore buzzSem = new Semaphore(0);
    Semaphore fizzBuzzSem = new Semaphore(0);
    Semaphore numSem = new Semaphore(0);

    public SemaphoreFizzBuzz(int n) {
        this.n = n;
    }

    public static void main(String[] args) {
        SemaphoreFizzBuzz fizzBuzz = new SemaphoreFizzBuzz(17);
        new Thread(() -> {
            try {
                fizzBuzz.fizz();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fizzBuzz.buzz();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fizzBuzz.fizzbuzz();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fizzBuzz.number();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * outputs "fizz". 3
     * @throws InterruptedException
     */
    public void fizz() throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if(i%3==0 && i%5!=0){
                fizzSem.acquire();
                System.out.print("fizz" + " ");
                numSem.release();
            }
        }
    }

    /**
     * outputs "buzz". 5
     * @throws InterruptedException
     */
    public void buzz() throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if(i%5==0 && i%3!=0){
                buzzSem.acquire();
                System.out.print("buzz" + " ");
                numSem.release();
            }
        }
    }

    /**
     * outputs "fizzbuzz". 3,5
     * @throws InterruptedException
     */
    public void fizzbuzz() throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if(i%5==0 && i%3==0){
                fizzBuzzSem.acquire();
                System.out.print("fizzbuzz" + " ");
                numSem.release();
            }
        }
    }

    /**
     * outputs "x".
     * @throws InterruptedException
     */
    public void number() throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if(i%3==0 && i%5!=0){
                fizzSem.release();
                numSem.acquire();
            } else if(i%5==0 && i%3!=0){
                buzzSem.release();
                numSem.acquire();
            } else if(i%5==0 && i%3==0){
                fizzBuzzSem.release();
                numSem.acquire();
            } else {
                System.out.print(i + " ");
            }
        }
    }
}
